var schedule = window.top.require('node-schedule');
/**
 * 定时同步本地上报记录
 */
function scheduleCronstyle() {
    //  cron：*/1 * * * *
    //  每隔分钟执行一次
    schedule.scheduleJob('*/1 * * * *', function () {
        console.log('schedule:', '同步本地上报记录')
        let selectSql = 'select * from t_trace_upload_record where enterprise_code = ? and process_status = ?';
        let selectData = [window.top.companyinfo.c_id, 0];
        //数据处理结果查询接口url
        let uploadInterfaceQueryUrl = apiArr[11].trim();
        let obj = {
            type: "POST",
            timeout: 6000,
            dataType: 'xml',
            url: uploadInterfaceQueryUrl,
            beforeSend: beforeSend
        }
        let promiseArr = [];
        db.selectBysql(selectSql, selectData,
            function (d) {
                d.forEach(function (item) {
                    obj.data = {
                        reqid: item.req_id
                    }
                    promiseArr.push(ajaxPromise(obj));
                })
                Q.all(promiseArr).then(arrs => {
                    arrs.forEach(function (item) {
                        syncDone(item);
                    })
                }).catch(function (e) {
                    log.error(e);
                });

            },
            function (err) {
                log.error(err);
            });
    });
}
scheduleCronstyle();


function beforeSend(xhr, settings) {
    xhr.setRequestHeader('signature', window.parent.companyinfo.signature);
    xhr.setRequestHeader('version', '1');
}

/**
 * 同步方法
 * @param {*} arrs 
 */
function syncDone(item) {
    let updateSql = 'update t_trace_upload_record set process_status = ? , process_res_filepath = ? where req_id = ?';
    let data = item.data;
    let req_id = item.obj.reqid;
    if (!data) {
        return;
    }
    let isSuccess = $(data).find('RESULT').attr('SUCCESS');
    //如果是正在处理中不进行后续操作
    if (isSuccess == 0) {
        return;
    }
    //返回的xml文件内容
    let content = data.documentElement.outerHTML.trim();
    let file = `${window.top.__dirname}/../../../temp/result/` + uuid.v1() + '.xml';
    //修改文件路径，在electron中带\符号路径下载出错
    file = file.replace(/\\/g, '/');
    let promise = Q.nfcall(fs.writeFile, file, content, 'utf8');
    promise.then(() => {
        let updateData = [];
        updateData.push(isSuccess);
        updateData.push(file);
        updateData.push(req_id);
        db.updateBysql(updateSql, updateData, function () {}, e => {
            log.error(e);
        });
    }).catch(err => {
        log.error(err)
    })
}